package db

import (
	"aquaman/app/infra/db/ctxdb"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gocraft/dbr/v2"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
)

var (
	dbKey = ctxdb.CtxKey{Key: "db"}
)


type DB struct {
	*ctxdb.CtxDB
}

func NewDBFromDbrConn(conn *dbr.Connection) *DB {
	return &DB{&ctxdb.CtxDB{Connection: conn, Key: dbKey}}
}

func NewDB(v *viper.Viper, log dbr.EventReceiver) *DB {
	config := v.Sub("database.aquaman")
	dsn := config.GetString("dsn")
	conn, err := dbr.Open("mysql", dsn, log)
	if err != nil {
		panic(errors.Wrapf(err, "Parse MySQL DSN failed: %s", dsn))
	}

	conn.SetMaxOpenConns(config.GetInt("max_open_conns"))


	return NewDBFromDbrConn(conn)
}